package com.brilliance.project.webapp.action.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.brilliance.project.common.Constants;
import com.brilliance.project.common.tools.MemoryFactory;
import com.brilliance.project.service.sysmanage.ILoginService;
import com.brilliance.project.webapp.action.BaseAction;
import com.brilliance.project.webapp.form.sysmanage.AgentForm;

@Scope("prototype")
@Component("loginAction")
public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	// 登录用户
	private AgentForm agent;

	public String excute() {
		return SUCCESS;
	}

	// 登录
	public String login() {
		if(null == agent){
			return SUCCESS;
		}
		this.clearFieldErrors();
		// List list = loginServiceImpl.query(new LoginSessionForm());
		// System.out.println(list.size());
		agent.setAgent_id(agent.getAgent_name());
		if (!"admin".equals(agent.getAgent_name())) {
			this.addFieldError("agent.agent_name", "用户名错误！");
			return SUCCESS;
		}

		if (Constants.IS_CHECK_LOGIN) {
			agent.setSessionId(getHttpServletRequest().getSession().getId());
			// 判断用户是否在其他地方已经登录
			if (isExistAgent()) {
				if ("Y".equals(agent.getKickOut())) {
					return "login";
				} else {
					// 假如已经登录，返回原画面，提示是否强制登出另一个用户
					this.addActionMessage("用户在其他地点登录，是否强迫退出？");
					this.setIfShowMsg(true);
					return SUCCESS;
				}
			}
		}
		session.put(Constants.SESSION_AGENT_KEY, agent);
		return "login";
	}

	/**
	 * 判读此用户是否已经登录
	 * 
	 * @return
	 */
	private boolean isExistAgent() {
		if (Constants.LOGIN_SYNCHRONIZATION
				.equals(Constants.LOGIN_SYNCHRONIZATION_AP)) {
			// AP：把用户ID和sessionId保存在ap memmory中
			return MemoryFactory.isExistAgent(agent, getContext());
		} else if (Constants.LOGIN_SYNCHRONIZATION
				.equals(Constants.LOGIN_SYNCHRONIZATION_DB)) {
			// AP：把用户ID和sessionId保存在DB中
			// Todo:
		}
		return true;
	}

	public AgentForm getAgent() {
		return agent;
	}

	public void setAgent(AgentForm agent) {
		this.agent = agent;
	}

}
